﻿@using Seal.Model;
@{
    ReportTask task = Model;

    task.TemplateDescription = "Execute a report.";

    //Parameters for this task
    task.Parameters.Add(new Parameter() { Name = "report_path", Value = "", DisplayName = "Report file path", Description = "The report file path (*.srex). The path can contain the '%SEALREPOSITORY%' keyword to specify the repository path." + ReportTask.TranslatedParameterDescriptionFull, Enums = new string[] { @"%SEALREPOSITORY%/Reports/Overview - Sales.srex", ReportTask.ParentExecResultKeyword, ReportTask.ExecInputKeyword }, UseOnlyEnumValues = false });
    task.Parameters.Add(new Parameter() { Name = "output_directory", Value = "", DisplayName = "Output directory", Description = "If not empty, the report result is saved in the report output directory."  + ReportTask.TranslatedParameterDescriptionFull, Enums = new string[] { @"%SEALREPOSITORY%/TestFiles/Results", ReportTask.ParentExecResultKeyword, ReportTask.ExecInputKeyword }, UseOnlyEnumValues = false });

    task.Script = @"@using System.Threading
@using System.IO
@using System.Data
@{
    ReportTask task = Model;
    var repository = task.Repository;

    var reportPath = task.GetValueTranslated(""report_path"");
    var outputDirectory = task.GetValueTranslated(""output_directory"");

    Report report = Report.LoadFromFile(reportPath, repository);
    report.ExecutionInitiator = task.Report;
    if (!string.IsNullOrEmpty(report.LoadErrors)) {
        task.LogMessage($""Error loading the report {reportPath}: {report.LoadErrors}"");
        task.Report.Cancel = true;
        return;
    }
    if (!string.IsNullOrEmpty(outputDirectory)) {
        if (!Directory.Exists(outputDirectory)) {
            Directory.CreateDirectory(outputDirectory);
        }
		var folderDevice = repository.Devices.First(i => i is OutputFolderDevice);
		var output = report.AddOutput(folderDevice);
		output.FolderPath = outputDirectory;
		report.OutputToExecute = output;
    }

	task.LogMessage($""Executing report '{reportPath}'"");
	ReportExecution execution = new ReportExecution() { Report = report };		
	execution.Execute();	
	while (report.Status != ReportStatus.Executed && !report.HasErrors && !report.Cancel) {
		Thread.Sleep(500);
        if (task.Report.Cancel) {
            report.Cancel = true;
        }
	}

    if (report.HasErrors) throw new Exception($""Error executing '{reportPath}':\r\n"" + report.ExecutionErrors);

	task.LogMessage($""Report '{reportPath}' has been executed"");
}
";

    task.BodyScript = ReportTask.BodyScriptTemplate;
}
